const date = new Date();
const app = getApp();
const dangqi_year_month = app.http.dangqi_year_monthPost;// 日期接口
Component({
  /**
   * 组件的属性列表
   */
  properties: {
    title: {
      type: String,  //标题
      value: ''
    },
    modelType: {
      type: String,  // select，   time 时间 ， date 日期  hour 小时  
      value: 'select'
    },
    selectArray: {
      type: null, // 类型（必填），目前接受的类型包括：String, Number, Boolean, Object, Array, null（表示任意类型）
      value: [],
      observer: function (newVal, oldVal) {
        //  this.setData({
        //    selectArray: newVal
        //  })
      }
    },
    selectIndex: {      //下标选中
      type: Array,
      value: null,
      observer: function (newVal, oldVal) {
        this.setData({
          selectIndex: newVal
        })
      }
    },
    dateIndex: {      //默认日期下标选中
      type: Array,
      value: null,
      observer: function (newVal, oldVal) {
        this.setData({
          dateIndex: newVal
        })
      }
    },
    timeIndex: {      //默认时间下标选中
      type: Array,
      value: null,
      observer: function (newVal, oldVal) {
        this.setData({
          timeIndex: newVal
          //,guodu: newVal
        })
      }
    },
    years: {      //年
      type: Array,
      value: [],
      observer: function (newVal, oldVal) {
      }
    },
    months: {      //月
      type: Array,
      value: [],
      observer: function (newVal, oldVal) {
      }
    },
    datetimeIndex: {      //默认日期下标选中
      type: Array,
      value: null,
      observer: function (newVal, oldVal) {
        this.setData({
          datetimeIndex: newVal
        })
      }
    },
  },

  //组件实例进入页面节点树时执行
  attached: function () {
    var that = this;
  
    //年
    var years = [];
    for (let i = date.getFullYear() - 10; i <= date.getFullYear() + 5; i++) {
      years.push('' + i)
    }
    // 获取月份
    var months = [];
    var current_m = date.getMonth();
    for (let i = 1; i <= 12; i++) {
      if (i < 10) {
        i = '0' + i
      }
      months.push('' + i)
    }
    // 获取日期 天数
    var days = [];
    var current_d = date.getDate();
    for (let i = 1; i <= 31; i++) {
      if (i < 10) {
        i = '0' + i
      }
      days.push('' + i)
    }
    //小时
    var hours = [];
    for (var i = 0; i < 24; i++) {
      if (i < 10) {
        i = '0' + i;
      }
      hours.push('' + i);
    }
    //分钟
    var minute = [];
    for (var i = 0; i < 60; i++) {
      if (i < 10) {
        i = '0' + i;
      }
      minute.push('' + i);
    }

    that.setData({
      yearsArr:years,
      monthsArr:months,
      days,
      hours,
      minute
    });

    let systemInfoSync = wx.getSystemInfoSync();
    //rpx
    let windowheight = systemInfoSync.windowHeight * (750 / systemInfoSync.windowWidth)
    let safeAreaBottom = (systemInfoSync.screenHeight - systemInfoSync.safeArea.bottom) * (750 / systemInfoSync.windowWidth)
    this.setData({
      windowheight,
      safeAreaBottom
    })

   
  },
  data: {
    years: [],
    months: [],
    days: [],
    hours: [],    //小时
    minute: [],    //分钟
    hideFlag: true, //模态框的状态  true-隐藏  false-显示
    guodu: null,   //picker-view 滑动时里面数据
    pickerScrolling: false, // pickerView是否正在滚动
  },
  //在组件布局完成后执行
  ready: function () {

  },
  //组件所在页面的生命周期
  pageLifetimes: {
    show: function () {
      // 页面被展示
    },
    hide: function () {
      // 页面被隐藏
      //关闭弹框
      this.hideModal();
    },
    resize: function (size) {
      // 页面尺寸变化
    }
  },
  methods: {
    //关闭取消
    mCancel: function () {
      var that = this;
      that.hideModal();
    },
    // 显示遮罩层 
    showModal: function () {
      var that = this;

      // 创建动画实例
      var animation = wx.createAnimation({
        duration: 400,//动画的持续时间
        timingFunction: 'ease',//动画的效果 默认值是linear->匀速，ease->动画以低速开始，然后加快，在结束前变慢
      })
      this.animation = animation; //将animation变量赋值给当前动画
      var time1 = setTimeout(function () {
        that.slideIn();//调用动画--滑入
        clearTimeout(time1);
        time1 = null;
      }, 100)
    },
    // 隐藏遮罩层 
    hideModal: function () {
      var that = this;
      var animation = wx.createAnimation({
        duration: 400,//动画的持续时间 默认400ms
        timingFunction: 'ease',//动画的效果 默认值是linear
      })
      this.animation = animation
      that.slideDown();//调用动画--滑出
      var time1 = setTimeout(function () {
        that.setData({
          hideFlag: true
        })
        clearTimeout(time1);
        time1 = null;
      }, 220)//先执行下滑动画，再隐藏模块
      //显示custom-tab-bar底部导航
      this.triggerEvent("customtabbar", { tabbarshow: true });
    },
    //动画 -- 滑入
    slideIn: function () {
      this.animation.translateY(0).step() // 在y轴偏移，然后用step()完成一个动画
      this.setData({
        //动画实例的export方法导出动画数据传递给组件的animation属性
        animationData: this.animation.export()
      })
    },
    //动画 -- 滑出
    slideDown: function () {
      this.animation.translateY(300).step()
      this.setData({
        animationData: this.animation.export(),
      })
    },
    // 返回月份的天数
    setDays(selectYear, selectMonth) {
      let num = parseInt(selectMonth);
      let temp = []
      if (num === 1 || num === 3 || num === 5 || num === 7 || num === 8 || num === 10 || num === 12) {
        // 判断31天的月份
        for (let i = 1; i <= 31; i++) {
          if (i < 10) {
            i = '0' + i
          }
          temp.push('' + i)
        }
      } else if (num === 4 || num === 6 || num === 9 || num === 11) { // 判断30天的月份
        for (let i = 1; i <= 30; i++) {
          if (i < 10) {
            i = '0' + i
          }
          temp.push('' + i)
        }
      } else if (num === 2) { // 判断2月份天数
        let year = parseInt(selectYear)
        //console.log(year)
        if (((year % 400 === 0) || (year % 100 !== 0)) && (year % 4 === 0)) {
          for (let i = 1; i <= 29; i++) {
            if (i < 10) {
              i = '0' + i
            }
            temp.push('' + i)
          }
        } else {
          for (let i = 1; i <= 28; i++) {
            if (i < 10) {
              i = '0' + i
            }
            temp.push('' + i)
          }
        }
      }
      return temp
    },
    //select 单个点击事件
    selectIndex: function (e) {
      //console.log(e);
      var index = e.target.dataset.index;
      var type = e.target.dataset.type;
      this.triggerEvent('index', { index: index, type: type })
      this.hideModal();
    },
    //日期date 滚动
    _binddateChange: function (e) {
      var that = this
      var dateIndex = e.detail.value
      //console.log(this.data.years, e.detail.value, this.data.dateIndex);
      //天数
      if (this.data.dateIndex[0] != dateIndex[0] || this.data.dateIndex[1] != dateIndex[1]){
        var days = this.setDays(this.data.years[dateIndex[0]], this.data.months[dateIndex[1]])
        that.setData({
          days: days
        })
      }
      //年改变时获取月份
      if (this.data.dateIndex[0] != dateIndex[0]) {
        that._getMonth(this.data.years[dateIndex[0]], function (errr, monthlist) {
          if (!errr) {
            that.setData({
              dateIndex: dateIndex,
              months: monthlist
            })
          } else {
            console.log(errr);
          }
        })
      } else {
        that.setData({
          dateIndex: dateIndex
        })
      }

    },
    //date 确定
    dateSure: function () {
      if (this.data.pickerScrolling) {
        return
      }
      var that = this;
      var dateIndex = this.properties.dateIndex
      var riqi = [];
      riqi[0] = that.data.years[parseInt(dateIndex[0])]
      riqi[1] = that.data.months[parseInt(dateIndex[1])]
      riqi[2] = that.data.days[parseInt(dateIndex[2])]
      this.triggerEvent("riqiSure", riqi);
      that.hideModal();
    },
    // time 滚动
    bindTimeChange: function (e) {
      var guodu = e.detail.value
      this.setData({
        guodu: guodu
      })
    },
    //time 确定
    timeSure: function () {
      if (this.data.pickerScrolling) {
        return
      }
      var that = this;
      var guodu = that.data.guodu;
      var riqi = [];
      riqi[0] = that.data.hours[parseInt(guodu[0])]
      riqi[1] = that.data.minute[parseInt(guodu[1])]
      this.triggerEvent("timeSure", riqi);
      that.hideModal();
    },
    //时间段选择
    bindtimeduanChange(e) {
      console.log(e)
      var guodu = e.detail.value
      this.setData({
        guodu: guodu
      })
    },
    //时间段确定
    timeduanSure() {
      if (this.data.pickerScrolling) {
        return
      }
      var index = 0
      if (this.data.guodu != null) {
        index = this.data.guodu[0];
      }
      this.triggerEvent("timeduanSure", { index: index });
      this.hideModal();
      this.setData({
        guodu: null
      })
    },
    //获取年
    _getYear(callback) {
      var token = wx.getStorageSync('userinfo').token
      var hall_id = wx.getStorageSync('hall_info').id
      dangqi_year_month({
        token,
        hall_id
      }, false).then(res => {
        if (res.code == 0) {
          callback(null, res.yearlist);
        } else {
          callback("获取年 接口失败");
        }
      })
    },
    //获取月
    _getMonth(year, callback) {
      var token = wx.getStorageSync('userinfo').token
      var hall_id = wx.getStorageSync('hall_info').id
      dangqi_year_month({
        token,
        hall_id,
        year
      }, false).then(res => {
        if (res.code == 0) {
          callback(null, res.monthlist);
        } else {
          callback("获取月 接口失败");
        }
      })
    },
    //datetime  滚动时
    _binddatetimeChange(e){
      var that = this
      var datetimeIndex = e.detail.value
      //天数
      if (this.data.datetimeIndex[0] != datetimeIndex[0] || this.data.datetimeIndex[1] != datetimeIndex[1]){
        console.log(this.data.yearsArr[datetimeIndex[0]], this.data.monthsArr[datetimeIndex[1]]);
        var days = this.setDays(this.data.yearsArr[datetimeIndex[0]], this.data.monthsArr[datetimeIndex[1]])
        console.log(days);
        that.setData({
          days: days
        })
      }
      that.setData({
        datetimeIndex
      })
    },
    //datetime 确定
    saveDatetime(){
      if (this.data.pickerScrolling) {
        return
      }
      var that = this;
      var dateIndex = this.properties.datetimeIndex
      var riqi = [];
      riqi[0] = that.data.yearsArr[parseInt(dateIndex[0])]
      riqi[1] = that.data.monthsArr[parseInt(dateIndex[1])]
      riqi[2] = that.data.days[parseInt(dateIndex[2])]
      riqi[3] = that.data.hours[parseInt(dateIndex[3])]
      riqi[4] = that.data.minute[parseInt(dateIndex[4])]
      this.triggerEvent("datetimeSure", {datetimeIndex:dateIndex,datetime:riqi});
      that.hideModal();
    },
    //开始
    pickstart(){
      this.setData({
        pickerScrolling: true
      })
    },
    picksend(){
      this.setData({
        pickerScrolling: false
      })
    }

  }
})
